<template>
  <countTo
    v-if="(Number(value) || Number(value) === 0) && value !== NaN && value !== null && value !== ''"
    class="child"
    :startVal="startVal"
    :endVal="endVal"
    :duration="duration"
    :decimals="decimals"
    separator=""
  />
  <span v-else>
    {{value}}
  </span>
</template>

<script>
import countTo from "vue-count-to";

export default {
  props: {
    value: {
      type: Number | String,
      default: 0,
    },
  },
  components: {
    countTo,
  },
  data() {
    return {
      startVal: 0,
      endVal: 0,
      duration: 2000,
      decimals: 0,
    };
  },
  watch: {
    value: {
      handler(newVal, oldVal) {
        this.endVal = Number(newVal);
        this.startVal = Number(oldVal);
      },
      deep: true,
    },
    // value(newVal, oldVal) {
      
    //   this.endVal = newVal;
    //   this.startVal = oldVal;
    // },
    endVal(newVal) {
      this.decimals = this.getDecimalPlaces(newVal);
    },
  },
  created() {
    this.endVal = Number(this.value);
  },
  methods: {
    getDecimalPlaces(num) {
      const str = num.toString();
      if (str.indexOf('.') === -1) return 0; // 无小数点
      return str.split('.')[1].length; // 返回小数位数
    }
  },
};
</script>

<style lang="scss" scope>
.child {
  display: inline-block;
  width: fit-content;
  font-weight: inherit; /* 强制继承父元素的 600 */
}
</style>
